// lib/auth.ts
import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';

interface UserPayload {
  id: string;
  username: string;
  email?: string;
  roles?: string[];
  iat?: number;
  exp?: number;
}

export async function getUserFromCookie(): Promise<UserPayload | null> {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('token')?.value;
    
    if (!token) {
      console.log('No token found in cookies');
      return null;
    }

    const secret = process.env.JWT_SECRET;
    if (!secret) {
      console.error('JWT_SECRET is not defined');
      return null;
    }

    const decoded = jwt.verify(token, secret) as UserPayload;
    console.log('User authenticated:', { id: decoded.id, username: decoded.username });
    
    return {
      id: decoded.id,
      username: decoded.username,
      email: decoded.email,
      roles: decoded.roles || []
    };
  } catch (error: any) {
    console.error('JWT verification failed:', error.message);
    return null;
  }
}

export async function isAuthenticated(): Promise<boolean> {
  const user = await getUserFromCookie();
  return user !== null;
}

export async function hasRole(role: string): Promise<boolean> {
  const user = await getUserFromCookie();
  return user?.roles?.includes(role) ?? false;
}
